package com.crm.miaohe.utils;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
@ConfigurationProperties(prefix = "id.generate")
public class IdGeneratorService {

    @Getter
    @Setter
    private Integer maxPerOrder;

    public static final String ORDER_NO_PREFIX = "mh";
    private static final Integer MAX_ORDER_DIGITS = 7;

    private final RedisTemplate<String, Integer> redisTemplate;

    public IdGeneratorService(RedisTemplate<String, Integer> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public String generateId(String key) {
        return generateId(key, 1L);
    }

    public String generateId(String key, Long delta) {
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddhhmmss"));
        RedisAtomicLong redisAtomicLong = new RedisAtomicLong(key,
                Objects.requireNonNull(redisTemplate.getConnectionFactory()));

        log.info("正在获取自增序列。[{}]", key);
        Long nextId = redisAtomicLong.getAndIncrement();
        redisAtomicLong.expire(1, TimeUnit.SECONDS);
        return ORDER_NO_PREFIX + timestamp + StringUtils.padRight(String.valueOf(nextId), MAX_ORDER_DIGITS, '0');
    }
}
